package org.example.config;

import io.moquette.broker.Server;
import io.moquette.broker.config.MemoryConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

@Slf4j
@Configuration
public class MqttAndBrokerConfig {

    /**
     * Mqtt服务器
     *
     * @return mqttBroker
     * @throws Exception 异常
     */
    @Bean
    public Server MqttBrokerServer() throws Exception {
        // MQTT broker 服务器
        Server mqttBroker = new Server();
        // 使用类加载器读取配置文件
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("moquette.conf")) {
            if (inputStream == null) {
                throw new FileNotFoundException("moquette.conf not found in classpath");
            }
            Properties configProps = new Properties();
            // 显式指定UTF-8编码
            configProps.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 设置关键配置的默认值
            configProps.putIfAbsent("host", "0.0.0.0");
            configProps.putIfAbsent("port", "1883");
            configProps.putIfAbsent("max_connections", "1000");
            configProps.putIfAbsent("websocket_port", "8087");

            // 启动服务器
            mqttBroker.startServer(new MemoryConfig(configProps));
            System.out.println("Moquette MQTT Broker started. Press Ctrl+C to shutdown.");
            // 程序关闭时执行的操作
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("Stopping Moquette MQTT Broker...");
                mqttBroker.stopServer();
                System.out.println("Moquette MQTT Broker Stopped.");
            }));
        } catch (Exception e) {
            // 捕获并输出异常信息。
            log.error("Failed to start MQTT broker", e);
            throw e;
        }
        return mqttBroker;
    }
}